﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Tetris
{
    class Handler
    {
        public event EventHandler KeyLeft;
        public event EventHandler KeyRight;
        public event EventHandler KeyUp;
        public event EventHandler KeyDown;

        protected virtual void OnKeyLeft()
        {
            if (KeyLeft != null)
            {
                KeyLeft(this, EventArgs.Empty);
            }
        }

        protected virtual void OnKeyRight()
        {
            if (KeyRight != null)
            {
                KeyRight(this, EventArgs.Empty);
            }
        }

        protected virtual void OnKeyUp()
        {
            if (KeyUp != null)
            {
                KeyUp(this, EventArgs.Empty);
            }
        }

        protected virtual void OnKeyDown()
        {
            if (KeyDown != null)
            {
                KeyDown(this, EventArgs.Empty);
            }
        }

        public static ConsoleKeyInfo ReadLastKey()
        {
            //Console.SetCursorPosition(0, 0);
            ConsoleKeyInfo keyPressed = new ConsoleKeyInfo();
            while (Console.KeyAvailable)
            {
                keyPressed = Console.ReadKey(true);
            }
            return keyPressed;
        }

        public void Control()
        {
            if (Console.KeyAvailable)
            {
                ConsoleKeyInfo key = ReadLastKey();

                switch (key.Key)
                {
                    case ConsoleKey.LeftArrow:
                        {
                            OnKeyLeft();
                            break;
                        }
                    case ConsoleKey.RightArrow:
                        {
                            OnKeyRight();
                            break;
                        }
                    case ConsoleKey.UpArrow:
                        {
                            OnKeyUp();
                            break;
                        }
                    case ConsoleKey.DownArrow:
                        {
                            OnKeyDown();
                            break;
                        }
                }

            }
        }

    }
}
